package com.itheima.sh.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
@PropertySource(value = {"classpath:jdbc.properties"})
public class jdbcConfig {
    //定义数据源
    @Value("${jdbc.driverClass}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;



    //定义获取数据源发方法
    @Bean(value = "druidDataSource")
    public DataSource getDruidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(user);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }


    //定义获取jdbcTemplate方法
    //@bean注解用于非自定义类 ioc容器自带的
    @Bean(value = "jdbcTemplate")      //在容器中寻找 数据源datasource 作为参数直接引入
    public JdbcTemplate getJdbcTemplate(@Qualifier("druidDataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}
